package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.MaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文引用素材信息表 服务实现类
 * </p>
 *
 * @author SpaceTraveller
 * @since 2022-11-09
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Override
    public WmMaterial uploadPic(String url, User user, int type) {
        WmMaterial material = new WmMaterial();
        material.setType(type);
        material.setUserId(user.getUserId());
        material.setUrl(url);
        material.setIsCollection(true);
        material.setCreatedTime(new Date());
        this.save(material);
        return material;
    }

    @Override
    public ResponseResult<List<WmMaterial>> listMaterial(MaterialDto dto) {
        User user = MediaThreadLocalUtil.get();
        if (user == null || user.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null) {
            query.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        query.eq(WmMaterial::getUserId,user.getUserId());
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> wmMaterialPage = this.page(page, query);
        PageResponseResult<List<WmMaterial>> pageResult = new PageResponseResult<>();
        pageResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        pageResult.setCurrentPage(dto.getPage());
        pageResult.setSize(dto.getSize());
        pageResult.setData(wmMaterialPage.getRecords());
        pageResult.setTotal(wmMaterialPage.getTotal());
        return pageResult;
    }
}
